import 'package:blurb/common/routers/names.dart';
import 'package:blurb/common/values/images.dart';
import 'package:blurb/common/values/svg.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
import 'package:blurb/common/store/share_store.dart';
import 'package:blurb/common/store/user_store.dart';
import 'package:blurb/common/store/comment_store.dart';
import 'package:blurb/common/models/share.dart';
import 'package:blurb/common/models/user.dart';
import 'package:blurb/common/models/comment.dart';
import 'package:blurb/common/services/user_service.dart';
import 'package:blurb/pages/community/sharing_publish.dart';

class SharingDetailPage extends StatefulWidget {
  final int shareId;

  const SharingDetailPage({super.key, required this.shareId});

  @override
  State<SharingDetailPage> createState() => _SharingDetailPageState();
}

class _SharingDetailPageState extends State<SharingDetailPage> {
  final TextEditingController _commentController = TextEditingController();
  Share? _share;
  User? _shareUser;
  List<Comment> _comments = [];
  bool _isLoading = true;
  
  @override
  void initState() {
    super.initState();
    _loadData();
  }
  
  @override
  void dispose() {
    _commentController.dispose();
    super.dispose();
  }
  
  // 加载分享和评论数据
  Future<void> _loadData() async {
    setState(() {
      _isLoading = true;
    });
    
    try {
      // 获取分享数据
      final shareStore = Provider.of<ShareStore>(context, listen: false);
      final shares = shareStore.shares;
      final share = shares.firstWhere((s) => s.id == widget.shareId);
      
      // 获取分享用户数据
      final shareUser = await UserService.getUserById(share.userId);
      
      // 获取评论数据
      final commentStore = Provider.of<CommentStore>(context, listen: false);
      final comments = await commentStore.getShareComments(widget.shareId);
      
      // 按时间排序评论，最新的在前面
      comments.sort((a, b) => DateTime.parse(b.time).compareTo(DateTime.parse(a.time)));
      
      setState(() {
        _share = share;
        _shareUser = shareUser;
        _comments = comments;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      print('Error loading data: $e');
    }
  }
  
  // 发表评论
  Future<void> _submitComment() async {
    if (_commentController.text.trim().isEmpty) {
      return;
    }
    
    final userStore = Provider.of<UserStore>(context, listen: false);
    final currentUser = userStore.currentUser;
    
    if (currentUser == null) {
      // 用户未登录
      _showLoginDialog(context);
      return;
    }
    
    try {
      final commentStore = Provider.of<CommentStore>(context, listen: false);
      
      final success = await commentStore.addComment(
        _commentController.text.trim(),
        currentUser.id,
        widget.shareId,
      );
      
      if (success) {
        _commentController.clear();
        // 只重新加载评论数据，不重新加载所有数据
        final comments = await commentStore.getShareComments(widget.shareId);
        comments.sort((a, b) => DateTime.parse(b.time).compareTo(DateTime.parse(a.time)));
        
        setState(() {
          _comments = comments;
        });
      }
    } catch (e) {
      print('Error submitting comment: $e');
    }
  }
  
  // 格式化时间
  String _formatTime(String timeStr) {
    final DateTime time = DateTime.parse(timeStr);
    final DateTime now = DateTime.now();
    final Duration difference = now.difference(time);

    if (difference.inDays > 365) {
      return '${(difference.inDays / 365).floor()} years ago';
    } else if (difference.inDays > 30) {
      return '${(difference.inDays / 30).floor()} months ago';
    } else if (difference.inDays > 0) {
      return '${difference.inDays} days ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours} hours ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes} minutes ago';
    } else {
      return 'just now';
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading || _share == null || _shareUser == null) {
      return Scaffold(
        backgroundColor: Colors.black,
        body: const Center(
          child: CircularProgressIndicator(
            color: Color(0xFF60C3FF),
          ),
        ),
      );
    }
    
    // 确定要显示的图片
    final String backgroundImage = _share!.pictures.isNotEmpty ? _share!.pictures[0] : _share!.picture;
    final bool hasPublishedImage = SharingPublishPage.publishedImages.containsKey(_share!.id);
    
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          // 上半部分背景图
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            height: MediaQuery.of(context).size.height * 0.45,
            child: ClipRRect(
              borderRadius: BorderRadius.only(
                bottomRight: Radius.circular(140),
              ),
              child: hasPublishedImage && SharingPublishPage.publishedImages[_share!.id]!.isNotEmpty
                  ? Image.memory(
                      SharingPublishPage.publishedImages[_share!.id]![0],
                      fit: BoxFit.cover,
                      alignment: Alignment.topCenter,
                    )
                  : Image.asset(
                      backgroundImage,
                      fit: BoxFit.cover,
                      alignment: Alignment.topCenter,
                    ),
            ),
          ),
          // 内容区域
          SafeArea(
            child: Column(
              children: [
                // 顶部导航栏
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      IconButton(
                        onPressed: () => Navigator.pop(context),
                        icon: Icon(
                          Icons.arrow_back_ios_new_rounded,
                          color: Colors.white,
                        ),
                      ),
                      Text(
                        'Details',
                        style: GoogleFonts.racingSansOne(
                          fontSize: 24.sp,
                          fontWeight: FontWeight.normal,
                          color: Colors.white,
                        ),
                      ),
                      IconButton(
                        icon: Icon(MSI.report, color: Colors.white),
                        onPressed: () {},
                      ),
                    ],
                  ),
                ),
                // 收藏按钮
                Align(
                  alignment: Alignment.centerRight,
                  child: Container(
                    margin: EdgeInsets.only(top: 230.h, right: 15.w),
                    width: 65.w,
                    height: 65.h,
                    child: Image.asset(
                      MIP.collectionBackground,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                SizedBox(height: 20.h),
                // 用户信息卡片
                Expanded(
                  child: Container(
                    width: double.infinity,
                    decoration: BoxDecoration(
                      color: Colors.black,
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(30.r),
                        topRight: Radius.circular(30.r),
                      ),
                    ),
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 用户信息卡片
                          Container(
                            margin: EdgeInsets.all(16.w),
                            padding: EdgeInsets.all(16.w),
                            decoration: BoxDecoration(
                              color: const Color(0xFF1F1F21),
                              borderRadius: BorderRadius.circular(16.r),
                            ),
                            child: Row(
                              children: [
                                // 头像
                                Container(
                                  width: 60.w,
                                  height: 60.h,
                                  decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    image: DecorationImage(
                                      image: AssetImage(_shareUser!.avatar),
                                      fit: BoxFit.cover,
                                    ),
                                  ),
                                ),
                                SizedBox(width: 12.w),
                                // 用户名和时间
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      _shareUser!.nickname,
                                      style: GoogleFonts.racingSansOne(
                                        fontSize: 24.sp,
                                        color: Colors.white,
                                      ),
                                    ),
                                    Text(
                                      _formatTime(_share!.time),
                                      style: TextStyle(
                                        color: Colors.white.withOpacity(0.7),
                                        fontSize: 14.sp,
                                      ),
                                    ),
                                  ],
                                ),
                                Spacer(),
                                // 关注按钮
                                Container(
                                  padding: EdgeInsets.symmetric(
                                    horizontal: 16.w,
                                    vertical: 8.h,
                                  ),
                                  decoration: BoxDecoration(
                                    gradient: LinearGradient(
                                      colors: [
                                        const Color(0xFF60C3FF),
                                        const Color(0xFFAADEFC),
                                      ],
                                    ),
                                    borderRadius: BorderRadius.circular(20.r),
                                  ),
                                  child: Row(
                                    children: [
                                      Icon(
                                        Icons.favorite_border,
                                        color: Colors.white,
                                        size: 16.sp,
                                      ),
                                      SizedBox(width: 4.w),
                                      Text(
                                        'Follow',
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                          // 帖子内容
                          Padding(
                            padding: EdgeInsets.symmetric(horizontal: 16.w),
                            child: Text(
                              _share!.description,
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 15.sp,
                                height: 1.5,
                              ),
                            ),
                          ),
                          // 如果有第二张图片，显示第二张图片
                          if (_share!.pictures.length > 1 || 
                              (hasPublishedImage && SharingPublishPage.publishedImages[_share!.id]!.length > 1))
                            Padding(
                              padding: EdgeInsets.all(16.w),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(12.r),
                                child: hasPublishedImage && SharingPublishPage.publishedImages[_share!.id]!.length > 1
                                    ? Image.memory(
                                        SharingPublishPage.publishedImages[_share!.id]![1],
                                        fit: BoxFit.cover,
                                        width: double.infinity,
                                        height: 200.h,
                                      )
                                    : Image.asset(
                                        _share!.pictures[1],
                                        fit: BoxFit.cover,
                                        width: double.infinity,
                                        height: 200.h,
                                      ),
                              ),
                            ),
                          SizedBox(height: 24.h),
                          Divider(
                            color: Colors.white.withOpacity(0.1),
                            thickness: 1,
                          ),
                          // 评论标题
                          Padding(
                            padding: EdgeInsets.all(16.w),
                            child: Text(
                              'Comment',
                              style: GoogleFonts.racingSansOne(
                                fontSize: 24.sp,
                                color: Colors.white,
                              ),
                            ),
                          ),
                          // 评论列表
                          ..._comments.map((comment) => _buildCommentItem(comment)),
                          SizedBox(height: 80.h), // 为底部输入框留出空间
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          // 底部评论输入框
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Stack(
              children: [
                // 蓝色底层
                Container(
                  height: 80.h,
                  decoration: BoxDecoration(
                    color: const Color(0xFF60C3FF),
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(32.r),
                      topRight: Radius.circular(32.r),
                    ),
                  ),
                ),
                // 黑色上层
                Positioned(
                  top: 3.h,
                  left: 0,
                  right: 0,
                  height: 78.h,
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.black,
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(30.r),
                        topRight: Radius.circular(30.r),
                      ),
                    ),
                    child: Row(
                      children: [
                        Expanded(
                          child: Container(
                            margin: EdgeInsets.symmetric(horizontal: 16.w),
                            height: 50.h,
                            padding: EdgeInsets.symmetric(horizontal: 16.w),
                            decoration: BoxDecoration(
                              color: const Color(0xFF2A2A2C),
                              borderRadius: BorderRadius.circular(25.r),
                            ),
                            child: TextField(
                              controller: _commentController,
                              style: TextStyle(color: Colors.white),
                              decoration: InputDecoration(
                                hintText: 'Join the discussion',
                                hintStyle: TextStyle(
                                  color: Colors.white.withOpacity(0.5),
                                ),
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.symmetric(vertical: 12.h),
                              ),
                            ),
                          ),
                        ),
                        Container(
                          width: 48.w,
                          height: 48.h,
                          decoration: BoxDecoration(
                            color: const Color(0xFF2A2A2C),
                            shape: BoxShape.circle,
                          ),
                          child: IconButton(
                            icon: Icon(MSI.camera, color: Colors.white),
                            onPressed: () {},
                          ),
                        ),
                        SizedBox(width: 12.w),
                        Container(
                          width: 48.w,
                          height: 48.h,
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              colors: [
                                const Color(0xFF60C3FF),
                                const Color(0xFFAADEFC),
                              ],
                            ),
                            shape: BoxShape.circle,
                          ),
                          child: IconButton(
                            icon: Icon(MSI.send, color: Colors.white),
                            onPressed: _submitComment,
                          ),
                        ),
                        SizedBox(width: 16.w),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 评论项组件
  Widget _buildCommentItem(Comment comment) {
    return FutureBuilder<User?>(
      future: UserService.getUserById(comment.userId),
      builder: (context, snapshot) {
        final String userName = snapshot.hasData && snapshot.data != null 
            ? snapshot.data!.nickname 
            : 'User ${comment.userId}';
        final String userAvatar = snapshot.hasData && snapshot.data != null 
            ? snapshot.data!.avatar 
            : MIP.avatar;
            
        return Container(
          margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          padding: EdgeInsets.all(16.w),
          decoration: BoxDecoration(
            color: const Color(0xFF1F1F21),
            borderRadius: BorderRadius.circular(16.r),
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 评论者头像
              Container(
                width: 45.w,
                height: 45.h,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  image: DecorationImage(
                    image: AssetImage(userAvatar),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              SizedBox(width: 12.w),
              // 评论内容
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Text(
                          userName,
                          style: GoogleFonts.racingSansOne(
                            fontSize: 16.sp,
                            color: Colors.white,
                          ),
                        ),
                        SizedBox(width: 8.w),
                        Text(
                          _formatTime(comment.time),
                          style: TextStyle(
                            color: Colors.white.withOpacity(0.5),
                            fontSize: 12.sp,
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 4.h),
                    Text(
                      comment.content,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 14.sp,
                        height: 1.4,
                      ),
                    ),
                  ],
                ),
              ),
              // 更多选项
              IconButton(
                icon: Icon(Icons.more_horiz, color: Colors.white),
                onPressed: () {},
                padding: EdgeInsets.zero,
                constraints: BoxConstraints(),
              ),
            ],
          ),
        );
      },
    );
  }
  // 显示登录提示对话框
  void _showLoginDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: const Color(0xFF1F1F21),
        title: Text(
          'Please login first',
          style: GoogleFonts.racingSansOne(
            color: Colors.white,
            fontSize: 24.sp,
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              'Cancel',
              style: GoogleFonts.racingSansOne(
                color: Colors.white70,
                fontSize: 18.sp,
                fontWeight: FontWeight.normal,
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              GoRouter.of(context).push(RNS.guide);
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  begin: Alignment(0.50, 0.00),
                  end: Alignment(0.50, 0.96),
                  colors: [Color(0xFF60C3FF), Color(0xFFAADEFC)],
                ),
                borderRadius: BorderRadius.circular(30.r),
              ),
            child: Text(
              'Go to login',
              style: GoogleFonts.racingSansOne(
                color: Colors.white,
                fontSize: 18.sp,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
